define([
    "static/app/tips",
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "static/app/zdyh/util/js/loading",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (tips, Util, Tool, SelectOrg, SearchBlock, Loading) {

    var getDistrictDataController = function () {
        return getServer() + "/yh/yhDisasters";
    };

    /**
     * 页面初始化
     */
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        initProvinceSelect("北京市", "北京市", "");
    };

    var initProvinceSelect = function (Province, City, Area) {
        var html = "";
        $("#citySelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        //debugger;
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#citySelect").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#citySelect').val(City);
                            var htmlArea = '';
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#areaSelect").append(htmlArea);
                                    $('#areaSelect').val(Area);
                                    // 列表
                                    //queryFxCertaintyLossDistrictsData();
                                    createYhDisasterGrid();
                                }
                            });

                        } else {
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    debugger;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#areaSelect").append(htmlArea);
                                                    $('#areaSelect').val(Area);
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#citySelect").append(htmlCity);
                                    $('#citySelect').val(City);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
                $('#provinceSelect').val(Province);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#citySelect").append(html);
                }
            });
        });
        $("#citySelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    };

    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            if ($("#provinceSelect").val() && $("#citySelect").val()) createYhDisasterGrid();
            else
                Util.alert('请选择省、市！');


        });
        /*$("#downLoad").click(function () {
            downLoadMain();
        });
        $("#export").click(function () {
                exportFile();
        });*/
        $("#btnReset").click(function () {
            $("#provinceSelect").val("");
            $("#citySelect").val("");
            $("#areaSelect").val("");
            $("#bearDisasterBodyType").val("");
            $("#sign").val("");
        });
    };
    var createYhDisasterGrid = function () {
        $("#yhDisasterGrid").datagrid({
            url: getDistrictDataController() + "/searchEvaluateRpheqResult",
            method: "POST",
            fitColumns: true,
            autoRowHeight: false,
            columns: [[
                {field: "ck", checkbox: true},
                {
                    field: 'province', sortable: true,
                    title: '省',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'city', sortable: true,
                    title: '市',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'area', sortable: true,
                    title: '区（县）',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'level',
                    title: '隐患等级',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'code',
                    title: '所属区县编号',
                    width: '20%',
                    align: 'center',
                },
            ]],
            toolbar: [{
                iconCls: 'fa fa-download',
                text: "下载",
                handler: function () {
                    downLoadMain();
                }
            }],
            onLoadSuccess: function () {
                $('#yhDisasterGrid').datagrid('checkAll');
            },
            queryParams: {
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
                bearDisasterBodyType: $("#bearDisasterBodyType").val(),
                sign: $("#sign").val(),
            },
            pagination: true,
            pageSize: 10
        });
    };

    var downLoadMain = function () {
        var rows = $('#yhDisasterGrid').datagrid('getSelections');
        if (rows.length == 0) {
            Util.alert("请勾选复选框再进行数据下载!");
            return ;
        }
        var taskDict = {"1" : false, "2": false};
        downLoad("1", taskDict);
        var t = setInterval(function () {
            if (taskDict["1"]) {
                clearInterval(t);
                exportFile("2", taskDict);
            }
        }, 50);

    };
    var downLoad = function (downLoadIndex, taskDict) {
        var province = $("#provinceSelect").val();
        var loading = Loading({ text : "正在下载【" + province + "】SHP文件..." });
        loading.show();
        // if (province)
        //     window.location.href = getDistrictDataController() + "/download?province=" + province;
        // else
        //     Util.alert('请选择省份！');

        var url = getDistrictDataController() + "/download?province=" + province;
        downloadAjax(url, downLoadIndex, loading, taskDict);
    }
    var exportFile = function (downLoadIndex, taskDict) {
        var rows = $('#yhDisasterGrid').datagrid('getSelections'), areas = "";
        for (var i = 0; i < rows.length; i++) {
            areas += rows[i].area + ",";
        }
        areas = areas.substring(0, areas.length - 1);
        console.log('areas: ', areas);

        var province = $("#provinceSelect").val();
        var city = $("#citySelect").val();
        var area = $("#areaSelect").val();
        var bearDisasterBodyType = $("#bearDisasterBodyType").val();
        var sign = $("#sign").val();
        //window.location.href = getDistrictDataController() + "/exportEvaluateRpheqResult?province="+province+"&city="+city+"&area="+area+"&bearDisasterBodyType="+bearDisasterBodyType+"&sign="+sign;
        var loading = Loading({ text : "正在下载所选区县数据..." });
        loading.show();
        var url = getDistrictDataController() + "/exportEvaluateRpheqResult?province="+province+"&city="+city+"&area="+areas+"&bearDisasterBodyType="+bearDisasterBodyType+"&sign="+sign;
        downloadAjax(url, downLoadIndex, loading, taskDict);
    }
    var downloadAjax = function (url, downLoadIndex, loading, taskDict) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);    // 也可以使用POST方式，根据接口
        xhr.responseType = "blob";  // 返回类型blob
        // 定义请求完成的处理函数，请求前也可以增加加载框/禁用下载按钮逻辑
        xhr.onload = function () {
            // 请求完成
            if (this.status === 200) {
                taskDict[downLoadIndex] = true;
                if (loading) loading.close();
                // 返回200
                var blob = this.response;
                var str = this.getResponseHeader("Content-Disposition");
                var index = str.lastIndexOf("=");
                str =str.substring(index+1,str.length);
                var reader = new FileReader();
                reader.readAsDataURL(blob);  // 转换为base64，可以直接放入a表情href
                reader.onload = function (e) {
                    // 转换完成，创建一个a标签用于下载
                    var a = document.createElement('a');

                    a.download = decodeURI(str);
                    a.href = e.target.result;
                    $("body").append(a);  // 修复firefox中无法触发click
                    a.click();
                    $(a).remove();
                    if (downLoadIndex == "2") Util.alert("下载成功!");
                }
            } else{
                if (downLoadIndex == "1") Util.alert("下载SHP文件出错!");
                if (downLoadIndex == "2") Util.alert("下载Excel文件出错!");
            }
        };
        xhr.send();
    };

    return {
        init: init
    };
});
